package com.geek.mysql7work.work1;

import com.geek.spring5work.JDBCUtils;

import java.io.FileReader;
import java.io.IOException;
import java.net.URL;
import java.sql.*;
import java.util.*;

public class DBManagerV1 {

    private static String user;
    private static String password;
    private static String url;
    private static String driver;


    /**
     * 静态代码块
     */
    static {
        // 读取资源文件，获取值
        try {
            // 创建Properties集合类
            Properties pro = new Properties();
            // 获取src路径
            ClassLoader classLoader = JDBCUtils.class.getClassLoader();
            URL res = classLoader.getResource("jdbc.properties");
            String path = res.getPath();
            // 加载文件
            pro.load(new FileReader(path));
            // 获取属性赋值
            url = pro.getProperty("url");
            user = pro.getProperty("user");
            password = pro.getProperty("password");
            driver = pro.getProperty("driver");
            // 注册驱动
            Class.forName(driver);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

    public Connection getConnection() {
        Connection conn = null;

        try {
            Class.forName(driver);
            conn = DriverManager.getConnection(url, user, password);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        }

        return conn;
    }

    public void close(ResultSet rs, Statement statement, Connection conn) {
        if (rs != null) {
            try {
                rs.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if (statement != null) {
            try {
                statement.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if (conn != null) {
            try {
                conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

    public void close(ResultSet rs, PreparedStatement ps, Connection conn) {
        if (rs != null) {
            try {
                rs.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if (ps != null) {
            try {
                ps.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if (conn != null) {
            try {
                conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 执行一条sql ( 没有使用预编译, 有sql 注入风险)
     *
     * @param sql
     */
    public void execute(String sql) {
        Connection conn = null;
        Statement statement = null;
        conn = getConnection();
        try {
            statement = conn.createStatement();
            statement.execute(sql);
        } catch (SQLException e) {
            System.out.println(sql);
            System.out.println("出错了");
            e.printStackTrace();
            if (conn != null) {
                // 事务回滚
                try {
                    conn.rollback();
                } catch (SQLException e1) {
                    e1.printStackTrace();
                }
            }
        } finally {
            close(null, statement, conn);
        }
    }

    /**
     * 批量执行多条 sqls, 一条失败全部回滚 ( 没有使用预编译, 有sql 注入风险)
     */
    public void executesBantch(List<String> sqls) {
        Connection conn = null;
        Statement statement = null;
        conn = getConnection();
        // 禁用自动提交
        try {
            statement = conn.createStatement();
            conn.setAutoCommit(false);

            for (String sql : sqls) {
                statement.addBatch(sql);
            }

            statement.executeBatch();

            // 提交事务
            conn.commit();
            conn.setAutoCommit(true);
        } catch (SQLException e) {
            for (String sql : sqls) {
                System.out.println(sql);
            }
            System.out.println("出错了");

            e.printStackTrace();
            if (conn != null) {
                // 事务回滚
                try {
                    conn.rollback();
                } catch (SQLException e1) {
                    e1.printStackTrace();
                }
            }
        } finally {
            close(null, statement, conn);
        }
    }

    /**
     * @param querySql 查询语句
     * @return Map<String       ,               Object> </br>
     * <p>
     * key : 列名</br>
     * value : 列值
     */
    public List<Map<String, Object>> query(String querySql) {
        Connection conn = null;
        PreparedStatement ps = null;
        conn = getConnection();
        try {
            ps = conn.prepareStatement(querySql);
            ResultSet rs = ps.executeQuery();
            List<Map<String, Object>> objMapList = new LinkedList<>();
            while (rs.next()) {
                Map<String, Object> objMap = new HashMap<String, Object>();
                ResultSetMetaData rsm = rs.getMetaData(); //获得列集
                int colCount = rsm.getColumnCount();   //获得列的个数
                for (int i = 0; i < colCount; i++) {
                    String colName = rsm.getColumnName(i + 1);
                    Object colValue = rs.getObject(colName);
                    objMap.put(colName, colValue);
                }
                objMapList.add(objMap);
            }

            return objMapList;
        } catch (SQLException e) {
            e.printStackTrace();
        }

        return null;
    }

    /**
     * 预编译的批量执行 （推荐）
     *
     * @param paramsList  参数列表
     * @param sqlTemplate sql 模板
     * @throws RuntimeException
     */
    public void bantchExecute(List<Object[]> paramsList, String sqlTemplate) throws RuntimeException {
        Connection conn = null;
        PreparedStatement ps = null;

        try {
            conn = getConnection();
            conn.setAutoCommit(false);
            ps = conn.prepareStatement(sqlTemplate);

            for (Object[] params : paramsList) {
                for (int i = 0; i < params.length; i++) {
                    ps.setObject(i + 1, params[i]);
                }
                ps.addBatch();
            }
            ps.executeBatch();

            // 提交事务
            conn.commit();
        } catch (SQLException e) {
            e.printStackTrace();
            if (conn != null) {
                // 事务回滚
                try {
                    conn.rollback();
                    throw new RuntimeException();
                } catch (SQLException e1) {
                    e1.printStackTrace();
                }
            }
        } finally {
            close(null, ps, conn);
        }
    }

    /**
     * 推荐使用， 安全高效
     *
     * @param sqlMaps</br> List<Object[]> paramList
     *                     String sqlTemplate
     * @throws RuntimeException
     */
    public void bantchExecute(LinkedHashMap<List<Object[]>, String> sqlMaps) throws RuntimeException {
        Connection conn = null;
        PreparedStatement ps = null;

        try {
            conn = getConnection();
            for (Map.Entry<List<Object[]>, String> sqlMap : sqlMaps.entrySet()) {
                conn.setAutoCommit(false);
                List<Object[]> paramList = sqlMap.getKey();
                String sqlTemplate = sqlMap.getValue();
                ps = conn.prepareStatement(sqlTemplate);

                for (Object[] params : paramList) {
                    for (int i = 0; i < params.length; i++) {
                        ps.setObject(i + 1, params[i]);
                    }
                    ps.addBatch();
                }

                ps.executeBatch();
                conn.commit();
            }
        } catch (SQLException e) {
            e.printStackTrace();
            if (conn != null) {
                // 事务回滚
                try {
                    conn.rollback();
                    throw new RuntimeException();
                } catch (SQLException e1) {
                    e1.printStackTrace();
                }
            }
        } finally {
            close(null, ps, conn);
        }
    }
}